<template>
  <van-nav-bar
    title="用户注册"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
  />

  <van-field v-model="tel" type="tel" label="请输入手机号" />

  <van-field
    v-model="sms"
    center
    clearable
    label="短信验证码"
    placeholder="请输入短信验证码"
  >
    <template #button>
      <van-button
        :disabled="tel.length !== 11"
        size="small"
        type="danger"
        @click="getSmsCode"
        >发送验证码</van-button
      >
    </template>
  </van-field>

  <van-field
    v-model="password"
    type="password"
    label="密码"
    placeholder="请输入密码"
  />

  <van-button @click="submit" :disabled="!flage" round type="danger"
    >确定</van-button
  >
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { Dialog } from "vant";
import { useRouter } from "vue-router";
import type { Ref } from "vue";
import { msgCode, userRegister } from "@/api/api";
import { Toast } from "vant";

interface IApiCode {
  code: string;
  data: number;
  message: string;
}

const tel = ref("");
const router = useRouter();
const sms: Ref<string | number> = ref("");
const password: Ref<string> = ref("");
const flage = computed(() => {
  return tel.value.length === 11 && sms.value && password.value;
});

const getSmsCode = () => {
  Dialog.confirm({
    title: "提示",
    message: `将向手机号：${tel.value}发送短信验证码`,
  })
    .then(async () => {
      const res = (await msgCode({
        tel: tel.value as string,
      })) as unknown as IApiCode;
      if (res.code === "200") {
        sms.value = res.data;
      }
    })
    .catch(() => {
      console.log("我取消了");
    });
};

const submit = async () => {
  const params = {
    tel: tel.value,
    password: password.value,
  };
  const res = (await userRegister(params)) as unknown as IApiCode;
  if (res.code === "200") {
    Dialog.confirm({
      title: "注册完成",
      message: "注册成功，立即去登陆？",
    })
      .then(async () => {
        router.push("/login");
      })
      .catch(() => {
        console.log("我取消了");
      });
  } else {
    Toast.fail("注册失败了");
  }
};
</script>

<style lang="scss" scoped>
.van-field {
  margin-top: 40px;
  background: #f1f1f1;
  border-radius: 30px;
  color: black;
  font-size: 16px;

}
.yanzhengmaaBtn{
  background:#FFF100;
  color: black;
}
.quedingBtn{
  color: black;
  background:#FFF100;
  margin-top: 30px;
  font-size: 20px;
}
</style>
